package com.xuecheng.manage_course.service;

import com.xuecheng.framework.domain.course.CoursePic;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.dao.CoursePicRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class CoursePicService {
    @Resource
    CoursePicRepository coursePicRepository;

    /**
     * 添加课程图片
     *
     * @param courseId 课程id
     * @param pic      课程图片地址
     * @return 响应结果
     */
    public ResponseResult addCoursePic(String courseId, String pic) {
        if (StringUtils.isEmpty(courseId) || StringUtils.isEmpty(pic)) {
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
        CoursePic coursePic = null;
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (optional.isPresent()) {
            coursePic = optional.get();
        }
        if (coursePic == null) {
            coursePic = new CoursePic();
        }
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 查找课程图片
     *
     * @param courseId 课程id
     * @return 响应结果
     */
    public CoursePic findCoursePic(String courseId) {
        return coursePicRepository.findById(courseId).get();
    }

    /**
     * 删除课程图片
     *
     * @param courseId 课程id
     * @return 响应结果
     */
    @Transactional
    public ResponseResult deleteCoursePic(String courseId) {
        long l = coursePicRepository.deleteByCourseid(courseId);
        if (l > 0) {
            return new ResponseResult(CommonCode.SUCCESS);
        } else {
            return new ResponseResult(CommonCode.FAIL);
        }
    }
}
